package com.hotel.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hotel.model.Booking;
import com.hotel.model.Room;
import com.hotel.service.HotelService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/hotel/*")
public class HotelController extends HttpServlet {
    private HotelService hotelService;
    private ObjectMapper objectMapper;
    
    @Override
    public void init() throws ServletException {
        hotelService = new HotelService();
        objectMapper = new ObjectMapper();
        System.out.println("HotelController 初始化完成");
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String pathInfo = request.getPathInfo();
        System.out.println("GET请求路径: " + pathInfo);
        System.out.println("完整请求URI: " + request.getRequestURI());
        
        if (pathInfo == null || pathInfo.equals("/")) {
            request.getRequestDispatcher("/jsp/index.jsp").forward(request, response);
        } else if (pathInfo.equals("/rooms")) {
            List<Room> rooms = hotelService.getAllRooms();
            request.setAttribute("rooms", rooms);
            request.getRequestDispatcher("/jsp/rooms.jsp").forward(request, response);
        } else if (pathInfo.equals("/available-rooms")) {
            List<Room> availableRooms = hotelService.getAvailableRooms();
            request.setAttribute("rooms", availableRooms);
            request.getRequestDispatcher("/jsp/available-rooms.jsp").forward(request, response);
        } else if (pathInfo.equals("/bookings")) {
            List<Booking> bookings = hotelService.getAllBookings();
            request.setAttribute("bookings", bookings);
            request.getRequestDispatcher("/jsp/bookings.jsp").forward(request, response);
        } else if (pathInfo.startsWith("/book/")) {
            String roomIdStr = pathInfo.substring(6);
            try {
                int roomId = Integer.parseInt(roomIdStr);
                Room room = hotelService.getRoomById(roomId);
                if (room != null) {
                    request.setAttribute("room", room);
                    request.getRequestDispatcher("/jsp/booking-form.jsp").forward(request, response);
                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        String pathInfo = request.getPathInfo();
        String requestURI = request.getRequestURI();
        
        System.out.println("POST请求路径: " + pathInfo);
        System.out.println("完整请求URI: " + requestURI);
        
        // 打印所有参数用于调试
        System.out.println("请求参数:");
        request.getParameterMap().forEach((key, values) -> {
            System.out.println("  " + key + " = " + String.join(", ", values));
        });
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 修复路径匹配问题
            if (pathInfo != null && pathInfo.equals("/book")) {
                // 处理预订请求
                System.out.println("处理预订请求");
                
                // 获取并验证参数
                String roomIdStr = request.getParameter("roomId");
                String customerName = request.getParameter("customerName");
                String customerPhone = request.getParameter("customerPhone");
                String customerEmail = request.getParameter("customerEmail");
                String checkInDateStr = request.getParameter("checkInDate");
                String checkOutDateStr = request.getParameter("checkOutDate");
                String totalAmountStr = request.getParameter("totalAmount");
                
                System.out.println("预订参数 - roomId: " + roomIdStr + ", customerName: " + customerName + 
                                 ", checkInDate: " + checkInDateStr + ", checkOutDate: " + checkOutDateStr + 
                                 ", totalAmount: " + totalAmountStr);
                
                // 参数验证
                if (roomIdStr == null || roomIdStr.trim().isEmpty() ||
                    customerName == null || customerName.trim().isEmpty() || 
                    customerPhone == null || customerPhone.trim().isEmpty() || 
                    checkInDateStr == null || checkInDateStr.trim().isEmpty() || 
                    checkOutDateStr == null || checkOutDateStr.trim().isEmpty() || 
                    totalAmountStr == null || totalAmountStr.trim().isEmpty()) {
                    
                    result.put("success", false);
                    result.put("message", "缺少必需的参数");
                } else {
                    Booking booking = new Booking();
                    booking.setRoomId(Integer.parseInt(roomIdStr.trim()));
                    booking.setCustomerName(customerName.trim());
                    booking.setCustomerPhone(customerPhone.trim());
                    booking.setCustomerEmail(customerEmail != null ? customerEmail.trim() : "");
                    
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    booking.setCheckInDate(new Date(sdf.parse(checkInDateStr.trim()).getTime()));
                    booking.setCheckOutDate(new Date(sdf.parse(checkOutDateStr.trim()).getTime()));
                    booking.setTotalAmount(new BigDecimal(totalAmountStr.trim()));
                    booking.setStatus("pending");
                    
                    boolean success = hotelService.bookRoom(booking);
                    
                    result.put("success", success);
                    result.put("message", success ? "预订成功！" : "预订失败，请重试。");
                }
                
            } else if (pathInfo != null && pathInfo.equals("/confirm")) {
                // 确认预订
                System.out.println("处理确认预订请求");
                
                String bookingIdStr = request.getParameter("bookingId");
                System.out.println("确认预订ID: " + bookingIdStr);
                
                if (bookingIdStr == null || bookingIdStr.trim().isEmpty()) {
                    result.put("success", false);
                    result.put("message", "缺少预订ID参数");
                } else {
                    int bookingId = Integer.parseInt(bookingIdStr.trim());
                    boolean success = hotelService.confirmBooking(bookingId);
                    
                    result.put("success", success);
                    result.put("message", success ? "预订已确认！" : "确认失败，请重试。");
                }
                
            } else if (pathInfo != null && pathInfo.equals("/cancel")) {
                // 取消预订
                System.out.println("处理取消预订请求");
                
                String bookingIdStr = request.getParameter("bookingId");
                String roomIdStr = request.getParameter("roomId");
                System.out.println("取消预订 - bookingId: " + bookingIdStr + ", roomId: " + roomIdStr);
                
                if (bookingIdStr == null || bookingIdStr.trim().isEmpty() || 
                    roomIdStr == null || roomIdStr.trim().isEmpty()) {
                    result.put("success", false);
                    result.put("message", "缺少必需的参数");
                } else {
                    int bookingId = Integer.parseInt(bookingIdStr.trim());
                    int roomId = Integer.parseInt(roomIdStr.trim());
                    boolean success = hotelService.cancelBooking(bookingId, roomId);
                    
                    result.put("success", success);
                    result.put("message", success ? "预订已取消！" : "取消失败，请重试。");
                }
            } else {
                result.put("success", false);
                result.put("message", "未知的请求路径: " + pathInfo);
            }
            
        } catch (Exception e) {
            System.err.println("处理请求时发生异常: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        // 返回JSON响应
        System.out.println("返回结果: " + result);
        objectMapper.writeValue(response.getWriter(), result);
    }
}
